import { NextRequest, NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase';

// 保存或更新会话记录
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userId, chatId, lastMessage } = body;

    if (!userId || !chatId || !lastMessage) {
      return NextResponse.json(
        { error: '缺少必要参数' },
        { status: 400 }
      );
    }

    const now = Date.now();
    const supabase = createAdminClient();

    // 先检查记录是否存在
    const { data: existingSession } = await supabase
      .from('vertu_metaself_chat_sessions')
      .select('*')
      .eq('chat_id', chatId)
      .single();

    let result;
    
    if (existingSession) {
      // 更新现有记录
      const { data, error } = await supabase
        .from('vertu_metaself_chat_sessions')
        .update({
          last_message: lastMessage,
          last_message_time: now,
          updated_at: now,
        })
        .eq('chat_id', chatId)
        .select()
        .single();

      if (error) throw error;
      result = data;
    } else {
      // 创建新记录
      const { data, error } = await supabase
        .from('vertu_metaself_chat_sessions')
        .insert({
          user_id: userId,
          chat_id: chatId,
          last_message: lastMessage,
          last_message_time: now,
          created_at: now,
          updated_at: now,
        })
        .select()
        .single();

      if (error) throw error;
      result = data;
    }

    return NextResponse.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error('保存会话记录失败:', error);
    return NextResponse.json(
      { error: '服务器内部错误', message: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    );
  }
}

// 获取用户的会话历史列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');

    if (!userId) {
      return NextResponse.json(
        { error: '缺少userId参数' },
        { status: 400 }
      );
    }

    const supabase = createAdminClient();

    // 查询该用户的所有会话，按最后消息时间倒序
    const { data: sessions, error } = await supabase
      .from('vertu_metaself_chat_sessions')
      .select('*')
      .eq('user_id', parseInt(userId))
      .order('last_message_time', { ascending: false })
      .limit(50); // 最多返回50条记录

    if (error) throw error;

    // 格式化返回数据
    const formattedSessions = (sessions || []).map((session) => ({
      chatId: session.chat_id,
      title: session.last_message.length > 30 
        ? session.last_message.substring(0, 30) + '...' 
        : session.last_message,
      updateTime: new Date(Number(session.last_message_time)).toISOString(),
      lastMessage: session.last_message,
      lastMessageTime: session.last_message_time,
    }));

    return NextResponse.json({
      success: true,
      data: {
        list: formattedSessions,
        total: formattedSessions.length,
      },
    });
  } catch (error) {
    console.error('获取会话列表失败:', error);
    return NextResponse.json(
      { error: '服务器内部错误', message: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    );
  }
}

